﻿<%@ WebHandler Language="C#" Class="Upload" %>

using System;
using System.Web;
using System.IO;
using System.Data;
using System.Xml;

public class Upload : IHttpHandler {
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        context.Response.Expires = -1;
        try
        {
            HttpPostedFile postedFile = context.Request.Files["Filedata"];
            string ID = context.Request["name"].ToString();
            string savepath = "";
            string tempPath = "";
			//tempPath = context.Request["folder"];
            string[] strArray = System.Text.RegularExpressions.Regex.Split(context.Request["folder"], "/");
            for (int i = 1; i < strArray.Length-2;i++ )
            {
                tempPath += strArray[i]+"/";
            }
            tempPath += strArray[strArray.Length-1];
			//If you prefer to use web.config for folder path, uncomment below line:
			//tempPath = System.Configuration.ConfigurationManager.AppSettings["FolderPath"]; 			
            savepath = context.Server.MapPath(tempPath);
            string filename = RenameImage(postedFile.FileName);
            string listFile =context.Server.MapPath("savefile/" + "Images_" + ID + ".xml");
            bool checkFile = false;// If exist return true
            if (File.Exists(listFile))
                checkFile = InsertXML(listFile, tempPath + "/" + filename);
            else
                checkFile = CreateAndInsertXML(context,"Images_" + ID + ".xml", tempPath + "/" + filename);
            if (checkFile)
            {
                if (!Directory.Exists(savepath))
                    Directory.CreateDirectory(savepath);
                postedFile.SaveAs(savepath + @"\" + filename);
                string strresult = "/" + strArray[1] + @"/"+"uploadify/" + tempPath + @"/" + filename;
                context.Response.Write(strresult);
                context.Response.StatusCode = 200;
            }
        }
        catch (Exception ex)
        {
            context.Response.Write("Error: " + ex.Message);
        }
    }
    private bool InsertXML(string path,string fileName)
    {
        try
        {
            DataRow dr;
            DataSet dt = new DataSet();
            dt.ReadXml(path);
            dr = dt.Tables[0].NewRow();
            dr["Image"] = fileName;
            dt.Tables[0].Rows.Add(dr);
            dt.WriteXml(path, XmlWriteMode.WriteSchema);
        }
        catch
        {
        }
        return true;
    }
    private bool CreateAndInsertXML(HttpContext context,string StoreName,string fileName)
    {
        try
        {
            XmlDocument xmlDoc = new XmlDocument();
            XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "");
            XmlElement rootNode = xmlDoc.CreateElement("Images");
            xmlDoc.InsertBefore(xmlDeclaration, xmlDoc.DocumentElement);
            xmlDoc.AppendChild(rootNode);
            XmlElement portal = xmlDoc.CreateElement("Image");
            XmlText portalText = xmlDoc.CreateTextNode(fileName);
            rootNode.AppendChild(portal);
            portal.AppendChild(portalText);
            xmlDoc.Save(context.Server.MapPath("savefile/"+StoreName));
            
        }
        catch(Exception) { 
            return false; 
        }
        return true;
    }
    private void createNode(string Image,XmlTextWriter writer)
    {
        writer.WriteStartElement("Image");
        writer.WriteString(Image);
        writer.WriteEndElement();
    }
    private string RenameImage(string FileName)
    {
        string NewName = String.Empty;
        try
        {
            NewName = DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second + DateTime.Now.Millisecond + FileName;
        }
        catch
        {
        }
        return NewName;
    }
    public bool IsReusable {
        get {
            return false;
        }
    }
}